package utilities.database;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;


/**
 * @author Geoffrey Shaw, Kristofer Deviat
 * 
 * SQLLoader class provides utilities for creating a customizable SQL Loader file.
 * Allows for the customization of the delimeter aswell as the file path.
 *
 */
public class SQLLoader{
	private String loader;
	
	/**
	 * Constructor for the SQLLoader class. generates the custom sql loader string and creates the file.
	 * @param loaderFile name of the sql loader file to be created
	 * @param csvFile name of csv file
	 * @param delimeter char containing the delimeter to be used in the file.
	 * @throws IOException
	 */
	public SQLLoader(String loaderFile, String csvFile, char delimeter) throws IOException {
		this.loader = "LOAD DATA\n" +
						"INFILE \"" + csvFile + "\"\n" +
						"REPLACE\n" +
						"INTO TABLE payroll_load\n" +
						"FIELDS TERMINATED BY '" + delimeter + "' OPTIONALLY ENCLOSED BY '\"'\n" +
						"TRAILING NULLCOLS\n" +
						"(payroll_date DATE \"Month dd, yyyy\",employee_id,amount,status)";
		
		createLoadFile(loaderFile);
		
		
	}

	@Override
	public String toString() {
		return loader;
	}
	
	
	/**
	 * Creates the sqlloader file with customizable options.
	 * @param fileName name of the sqlloader file to be created
	 * @throws IOException
	 */
	public void createLoadFile(String fileName) throws IOException {		
		File file = new File(fileName);
		FileWriter fw = new FileWriter(file);
		
		if (!file.exists()) {
			file.createNewFile();
		}
		
		BufferedWriter bw = new BufferedWriter(fw);
		
		bw.write(loader);
		
		bw.close();
	}
}
